package com.tanhua.app.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.*;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.config.template.AipTemplate;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.model.pojo.Question;
import com.tanhua.model.pojo.Settings;
import com.tanhua.model.pojo.User;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UsersService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UsersApi usersApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    //根据id查询用户详情
    public UserInfoVo findUserInfo(Long userID) {
        //1 根据id查询用户详情
        UserInfo userInfo = userInfoApi.findById(userID);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo);

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.updateById(userInfo);
    }

    public SettingsVo findSettings() {
        //1. 创建vo对象
        SettingsVo vo = new SettingsVo();

        //2. 设置用户id和手机号
        vo.setId(UserHolder.getUserId());
        vo.setPhone(UserHolder.getMobile());

        //3. 根据用户id查询陌生人问题
        Question question = questionApi.findById(UserHolder.getUserId());
        //获取陌生人的问题，如果有值，就是用该值，如果没有值，设置默认的问题
        String txt = question == null ? "你喜欢java吗?" : question.getTxt();
        vo.setStrangerQuestion(txt);

        //4. 根据用户id查询通知设置数据
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if (settings != null) {
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
        }

        //返回结果
        return vo;
    }

    //保存陌生人问题
    public void questions(String content) {
        //1. 根据用户id查询陌生人问题
        Question question = questionApi.findById(UserHolder.getUserId());

        //2. 判断数据是否存在
        if (question == null) {
            //不存在就新增
            question = new Question();
            question.setUserId(UserHolder.getUserId());
            question.setTxt(content);

            questionApi.save(question);
        } else {
            //存在就修改
            question.setTxt(content);
            questionApi.update(question);
        }

    }

    //通知设置 - 保存
    public void notifications(Map param) {
        Boolean likeNotification = (Boolean) param.get("likeNotification");
        Boolean pinglunNotification = (Boolean) param.get("pinglunNotification");
        Boolean gonggaoNotification = (Boolean) param.get("gonggaoNotification");

        //1 根据用户id查询通知设置
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());

        //2 判断通知设置数据是否存在
        if (settings == null) {
            //不存在就新增
            settings = new Settings();
            settings.setUserId(UserHolder.getUserId());
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);

            settingsApi.save(settings);
        } else {
            //存在就更新
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);

            settingsApi.update(settings);
        }


    }

    //分页查询黑名单
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1 调用API分页查询 当前用户 的黑名单用户的用户详情
        Page<UserInfo> pages = userInfoApi.findByPage(UserHolder.getUserId(), page, pagesize);
        List<UserInfo> userInfoList = pages.getRecords();
        return new PageResult(page, pagesize, (int) pages.getTotal(), userInfoList);

        ////2 封装返回的用户详情vos
        //List<UserInfoVo> vos = new ArrayList<>();
        //for (UserInfo userInfo : pages.getRecords()) {
        //    UserInfoVo vo = new UserInfoVo();
        //    BeanUtils.copyProperties(userInfo, vo);
        //    if (userInfo.getAge() != null) {
        //        vo.setAge(userInfo.getAge().toString());
        //    }
        //
        //    vos.add(vo);
        //}
        //
        ////3 封装返回的分页对象
        //return new PageResult(page, pagesize, (int) pages.getTotal(), vos);
    }

    //移除黑名单用户
    public void deleteBlacklist(Long uid) {
        //调用Api，实现删除功能
        blackListApi.deleteBlacklist(UserHolder.getUserId(), uid);
    }


    private String CHECK_CODE = "check_code_";

    //发送短信验证码 修改手机号
    public void login(String phone) throws Exception {

        String code = "123456";
        //3 把验证码保存到redis中，以后要进行校验     设置验证码有效时间是5分钟
        //redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        redisTemplate.opsForValue().set(CHECK_CODE + phone, code, Duration.ofMinutes(5));

    }

    public Boolean yanzhengma(String verificationCode) {
        //1. 从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(CHECK_CODE + UserHolder.getMobile());

        //校验验证码，如果错误，抛异常
        //为空  或者   验证码不一致  抛异常
        if (StringUtils.isBlank(redisCode) || !redisCode.equals(verificationCode)) {
            //throw new RuntimeException("手机验证码错误");
            throw new BusinessException(ErrorResult.loginError());
        } else {
            return true;
        }
    }

    public void update(String phone) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.调用api保存手机号
        userApi.updatePhoneById(userId, phone);

        Map params = new HashMap();
        params.put("id", userId);
        params.put("mobile", phone);
    }

    public void updateHeader(MultipartFile headPhoto) throws Exception {
        //将头像上传到阿里云oss
        String imageUrl = ossTemplate.uploadOss(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        //2.调用百度云判断是否包含人脸
        boolean detect = aipTemplate.detect(imageUrl);
        if (!detect) {
            throw new RuntimeException("不包含人脸!");
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setAvatar(imageUrl);
            userInfo.setId(UserHolder.getUserId());
            userInfoApi.updateById(userInfo);
        }
    }
}




